import { useEffect, useState } from 'react'

interface ResourcePreloaderProps {
    resources: string[]
    onComplete?: () => void
    onProgress?: (progress: number) => void
}

const ResourcePreloader: React.FC<ResourcePreloaderProps> = ({
    resources,
    onComplete,
    onProgress
}) => {
    const [loadedCount, setLoadedCount] = useState(0)
    const [isComplete, setIsComplete] = useState(false)

    useEffect(() => {
        if (resources.length === 0) {
            setIsComplete(true)
            onComplete?.()
            return
        }

        let completedCount = 0

        const loadResource = (url: string): Promise<void> => {
            return new Promise((resolve, reject) => {
                // 判断资源类型
                if (url.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i)) {
                    const img = new Image()
                    img.onload = () => resolve()
                    img.onerror = () => reject(new Error(`Failed to load image: ${url}`))
                    img.src = url
                } else if (url.match(/\.(mp3|wav|ogg|m4a)$/i)) {
                    const audio = new Audio()
                    audio.oncanplaythrough = () => resolve()
                    audio.onerror = () => reject(new Error(`Failed to load audio: ${url}`))
                    audio.src = url
                } else if (url.match(/\.(mp4|webm|ogg)$/i)) {
                    const video = document.createElement('video')
                    video.oncanplaythrough = () => resolve()
                    video.onerror = () => reject(new Error(`Failed to load video: ${url}`))
                    video.src = url
                } else {
                    // 其他资源使用fetch
                    fetch(url)
                        .then(() => resolve())
                        .catch(() => reject(new Error(`Failed to load resource: ${url}`)))
                }
            })
        }

        const loadAllResources = async () => {
            try {
                await Promise.allSettled(
                    resources.map(async (url) => {
                        try {
                            await loadResource(url)
                            completedCount++
                            setLoadedCount(completedCount)
                            onProgress?.(completedCount / resources.length)
                        } catch (error) {
                            console.warn(`Failed to preload resource: ${url}`, error)
                            completedCount++
                            setLoadedCount(completedCount)
                            onProgress?.(completedCount / resources.length)
                        }
                    })
                )

                setIsComplete(true)
                onComplete?.()
            } catch (error) {
                console.error('Resource preloading failed:', error)
                setIsComplete(true)
                onComplete?.()
            }
        }

        loadAllResources()
    }, [resources, onComplete, onProgress])

    return null // 这是一个无UI组件
}

export default ResourcePreloader
